<?php

namespace app\api\controller;

use app\admin\controller\Sample;
use app\api\controller\Auth;
use app\api\model\Token;
use app\api\model\User as userModel;
use app\common\controller\ApiController;
use app\Request;
use Icharle\Wxtool\Wxtool;
use think\App;
use think\facade\Db;
use think\facade\Log;
use app\api\controller\JSSDK;


class User extends ApiController
{
    protected $noNeedLogin = [
        'wx_login',
        'getopenid',
        'getphone',
        "get_location",
        "wx_newlogin",
        "comlogin",
        "testing_smsSend",
        "sms_codelogin"
    ];
    /**
     * 登录
     * @return string
     * @throws \Exception
     */
    public function wx_login(userModel $user)
    {
        $param = $this->request->param();
       
        $wx = new Wxtool();
        if (empty($param['code'])) {
            $this->error("参数有误");
        }
        // if (empty($param['code']) || empty($param['encryptedData']) || empty($param['iv'])) {
        //     $this->error("参数有误");
        // }
        $code = $param['code'];
        // $encryptedData = urldecode($param['encryptedData']);
        // $iv = urldecode($param['iv']);
        $res = $wx->GetSessionKey($code);

        $nickName = nickname();
        $avatarUrl = "https://ls.yquewx.com/upload/login.jpg";

        $openId = $res['openid'];
      //  $unionId = empty($res['unionid']) ? '' : $res['unionid'];
        $isExit = $user->where('wx_openid', $openId)->find();
        //'unionId' => $unionId,   "nickname" => $nickName, 
        $saveData = ['update_time' => time(), 'avatar' => $avatarUrl];
        if (!empty($isExit)) {
            $uid = $isExit['id'];
            $ret = $user->where('id', $uid)->update($saveData);
            $gender = $isExit["gender"];
            $nickName = $isExit["nickname"];
        } else {
            $user = new userModel();
            $saveData['wx_openid'] = $openId;
            $saveData['nickname'] = $nickName;
            $ret = $user->save($saveData);
            $uid = $user->id;
            $gender = $user->gender;
        }  
        if ($ret) {
            $token = Auth::makeToken();
            $userToken = new Token();
            $userToken->setToken($token, $uid, $this->method);
            $user_info = ['nickname' => $nickName, 'avatar' => $avatarUrl,"uid"=>$uid,"gender"=>$gender];
            $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'user_info' => $user_info]);
        } else {
            $this->error('登陆失败,请稍后重试001');
        }
    }


    public function getopenid(){
        $param = $this->request->param();
        $wx = new Wxtool();
        if (empty($param['code'])) {
            $this->error("参数有误");
        }
        $code = $param['code'];
        $res = $wx->GetSessionKey($code);
        $this->success('登录成功', $res);
    }

    public function getphone(userModel $user){
        $param = $this->request->param();
        $wx = new Wxtool();
        // if (empty($param['session_key']) || empty($param['encryptedData']) || empty($param['iv']) || empty($param['openid'])) {
        //     $this->error("参数有误");
        // }
        if (empty($param['code']) || empty($param['encryptedData']) || empty($param['iv'])) {
            $this->error("参数有误");
        }
        $code = $param['code'];
        $res = $wx->GetSessionKey($code);
       
        $encryptedData = urldecode($param['encryptedData']);
        $iv = urldecode($param['iv']);
        $userinfo = $wx->GetUserInfo($encryptedData, $iv,$res['session_key']);
        $userinfo = json_decode($userinfo, true);
        $openId = $res['openid'];
        $phone = empty($userinfo['phoneNumber']) ? '' : $userinfo['phoneNumber'];
        //dump($phone);die;
        //'unionId' => $unionId,
        //$unionId = empty($param['unionid']) ? '' : $param['unionid'];
        $nickName = nickname();
        $avatarUrl = "https://ls.yquewx.com/upload/login.jpg";
        $isExit = $user->where('wx_openid', $openId)->find();
        $saveData = [ 'update_time' => time(), 'gender' => 0, 'avatar' => $avatarUrl,'phone' => $phone];
        if (!empty($isExit)) {
            $uid = $isExit['id'];
            $ret = $user->where('id', $uid)->update($saveData);
            $nickName = $isExit["nickname"];
            
        }else {
            $user = new userModel();
            $saveData['wx_openid'] = $openId;
            $saveData['nickname'] = $nickName;
            $ret = $user->save($saveData);
            $uid = $user->id;
        }
        // file_put_contents('wx.log', "ret:" . $ret . PHP_EOL, FILE_APPEND);
        if ($ret) {
            $token = Auth::makeToken();
            $userToken = new Token();
            $userToken->setToken($token, $uid, $this->method);
            $user_info = ['nickname' => $nickName, 'phone' => $phone,'avatar' => $avatarUrl,"uid"=>$uid];
            $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'user_info' => $user_info]);
        } else {
            $this->error('登陆失败，请稍后重试1');
        }
        
    }
    //获取定位参数
    public function get_location(){
        $jssdk = new JSSDK("wxe2943a6ef9364385","8c877d24139000d6ca2274dee731ca5d");//填写公众号 密匙
        $signPackage = $jssdk->GetSignPackage();
        $this->success('获取成功', $signPackage);
    }

    //用户登录
    public function wx_newlogin(userModel $user)
    {
        $param = $this->request->param();
        if (empty($param['code'])) {
            $this->error("参数有误");
        }
        $accop = $this->get_access_token_openid($param['code']);
       
        $userinfo = $this->get_userinfoarea($accop["access_token"],$accop["openid"]);
       
        $isExit = $user->where('wx_openid', $userinfo['openid'])->find();
        $saveData = ['nickname' => $userinfo['nickname'],'gender' => $userinfo['sex'],'avatar' => $userinfo['headimgurl'],"wx_openid"=>$userinfo["openid"]];
        if (!empty($isExit)) {
            $uid = $isExit['id'];
            $ret = $user->where('id', $uid)->update($saveData);
            $gender = $isExit["gender"];
            $nickName = $isExit["nickname"];
            $avatarUrl = $isExit["avatar"];
        } else {
            $user = new userModel();
            $ret = $user->save($saveData);
            $uid = $user->id;
            $gender = $user->gender;
            $avatarUrl = $user->avatar;
            $nickName = $user->nickname;
        }  
        if ($ret) {
            $token = Auth::makeToken();
            $userToken = new Token();
            $userToken->setToken($token, $uid, $this->method);
            $user_info = ['nickname' => $nickName, 'avatar' => $avatarUrl,"uid"=>$uid,"gender"=>$gender];
            $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'user_info' => $user_info]);
        } else {
            $this->error('登陆失败,请稍后重试');
        }
    }

    //获取access_token和openid
    public function get_access_token_openid($code){
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxe2943a6ef9364385&secret=8c877d24139000d6ca2274dee731ca5d&code=".$code."&grant_type=authorization_code";
        $result = Curl::get($url);
        $data = json_decode($result, true);
   
        return [
            "access_token"=>$data["access_token"],
            "openid"=>$data["openid"],
        ];

    }

    //获取用户信息
    public function get_userinfoarea($access_token,$openid){
 
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        $result = Curl::get($url);
        $data = json_decode($result, true);
        return [
            "openid"=>$data["openid"],
            "nickname"=>$data["nickname"],
            "sex"=>$data["sex"],
            "headimgurl"=>$data["headimgurl"]
        ];


    }


      //商家登陆  $2y$10$E1DvQqPnsAgK4pPLGUUK4uO1k0dYiZheq/iLnsRk//VYeQSJFl./.
      public function comlogin()
      {
          $param = $this->request->param();
          $rule = [
              'username|用户名'      => 'require',
              'password|密码'       => 'require'
          ];
          $this->validate($param, $rule);
          $company = Db::connect('tmp')->table('company')->where("mobile",$param['username'])->find();
          if (empty($company)) {
              $this->error('商户不存在');
          }
          if (password($param['password']) != $company["password"]) {
              $this->error('密码输入有误');
          }
          if ($company) {
              $token = Auth::makeToken();
              $user_token = Db::connect('tmp')->table('user_token')->where("user_id",$company["id"])->find();
              if(empty($user_token)){
                Db::connect('tmp')->table('user_token')->insert(["token"=>$token,"user_id"=>$company["id"],"type"=>$this->method]);
              }else{
                Db::connect('tmp')->table('user_token')->where("user_id",$company["id"])->update(["token"=>$token]);
              }
              $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'company_info' => $company]);
          } else {
              $this->error('登陆失败,请稍后重试');
          }

 
      }

   
      //短信验证码登录
      public function sms_codelogin(){
            $param = $this->request->param();
            $rule = [
                'phone|手机号'      => 'require|mobile',
                'code|验证码'       => 'require'
            ];
            $this->validate($param, $rule);
            // $flag = $this->verifyCode($param["code"],$param["phone"],1);
            // if(!$flag){
            //     $this->error('验证码错误或已过期');
            // }
            $company = Db::connect('tmp')->table('company')->where("mobile",$param['phone'])->find();
            $token = Auth::makeToken();
            if(empty($company)){
                //账号不存在注册
                Db::connect('tmp')->table('company')->insert(["mobile"=>$param["phone"],"cur_type"=>2,"created_at"=>date("Y-m-d H:i:s",time())]);
                $companyId = Db::connect('tmp')->table('company')->getLastInsID();
                Db::connect('tmp')->table('user_token')->insert(["token"=>$token,"user_id"=>$companyId,"type"=>$this->method]);
                $company_info = Db::connect('tmp')->table('company')->where("id",$companyId)->find();
                $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'company_info' => $company_info]);
            }else{
                //账号存在直接登陆
                $user_token = Db::connect('tmp')->table('user_token')->where("user_id",$company["id"])->find();
                if(empty($user_token)){
                    Db::connect('tmp')->table('user_token')->insert(["token"=>$token,"user_id"=>$company["id"],"type"=>$this->method]);
                }else{
                    Db::connect('tmp')->table('user_token')->where("user_id",$company["id"])->update(["token"=>$token]);
                }
                $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'company_info' => $company]);
            }
      }



    //发送短信验证码
    public function testing_smsSend(){
        $param = $this->request->param();
        $rule = [
            'phone|手机号'      => 'require'
        ];
        $this->validate($param, $rule);
        $param['sms_type'] = 1;
        $count = Db::connect('tmp')->table('sms')->where('phone', $param['phone'])->where('status', 2)->whereDay('ctime')->count();
        if ($count >= 5) {
            $this->error('今日发送短信已达上限');
        }
        $code = rand(10000, 99999);
        $smsData = Db::connect('tmp')->table('sms')->where('phone', $param['phone'])->where('sms_type', $param['sms_type'])->where('delete_time',0)->find();
        if ($smsData) {
            Db::connect('tmp')->table('sms')->where('id', $smsData['id'])->update(['delete_time' => time()]);
        }
        $smsdata = ['phone' => $param['phone'], 'code' => $code, 'sms_type' => $param['sms_type'], 'expire_time' => strtotime('+ 5 minute'), 'ctime' => time()];
        $rst = Db::connect('tmp')->table('sms')->insert($smsdata);
        if ($rst) {
            $smsId = Db::connect('tmp')->table('sms')->getLastInsID();
            $ret = $this->newSms($param['phone'], $code);
            if ($ret['code'] == 1) {
                Db::connect('tmp')->table('sms')->where('id', $smsId)->update(['status' => 2,"error_msg"=>$ret["msg"]]);
                $this->success('验证码发送成功');
            } else {
                Db::connect('tmp')->table('sms')->where('id', $smsId)->update(['status' => 3,"error_msg"=>$ret["msg"]]);
                $this->error('验证码发送失败');
            }
        } else {
            $this->error('验证码发送失败');
        }
    }

    /**
     * 校验验证码
    */
    public function verifyCode($code, $phone, $sms_type)
    {
        $smsData = Db::connect('tmp')->table('sms')
            ->where('phone', $phone)
            ->where('sms_type', $sms_type)
            ->where('code', $code)
            ->where('delete_time', 0)
            ->where('expire_time', '>', time())
            ->find();
        if (empty($smsData)) {
            return false;
        } else {
            return true;
        }
    }

     /**
     * 获取验证码
     * @return [type] [description]
     */
    public function Newsms($phone, $code)
    {
        $args = [
            "phoneNumbers" => $phone,
            "signName" => "子米无限",
            "templateCode" => 'SMS_470525124',
            "templateParam" => "{\"code\":\"" . $code . "\"}"
        ];
        $result = Sample::main($args);
        $result = json_decode($result, true);
        if ($result['body']['Code'] == 'OK') {
            return ['code' => 1,"msg"=>$result['body']['Message']];
        } else {
            return ['code' => 0,"msg"=>$result['body']['Message']];
        }
    }
  



     


}
